package Send2ME::Update::Personal;

use Send2ME::Dao::Auth;
use Send2ME::Dao::User;

use Send2ME::Magic::Magic;

use Dancer ':syntax';


prefix '/update/personal';

get '/' => sub {
	template 'personal', { credential => credential };
};

post '/' => sub {
	my($name, $recipient) = (params->{name}, params->{recipient});
	
	if (!$recipient || length($recipient) < 3) {
		redirect '/update/personal/?error=recipient-small';
		return;
	}
	
	if (!isAcceptable($recipient)) {
		redirect '/update/personal/?error=recipient-invalid';
		return;
	}
	
	my $user = undef;
	
	if (credential->{logged_in} && credential->{user}->{id}) {
		$user = getUser({ id => credential->{user}->{id}});		
	} 
	
	if (!$user) {
		status 'forbidden';
		return "Sorry, you can`t do this, cause you not logged.";
	}
	
	if (!isRecipientUnique($recipient)) {
		redirect '/update/personal/?error=recipient-unique';
		return;
	}
	
	$user->{name} = $name; 
	$user->{recipient} = $recipient;
	
	updateUser($user);
	currentUser($user);
	
	redirect '/';
};

sub isRecipientUnique {
	my $recipient = shift;
	return !getUser({  recipient => $recipient });
}

1;